/*
 * Copyright (C) 2007 Eskil Bylund
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

using System;
using System.IO;
using System.Security.Cryptography;

namespace DCSharp.Hashing
{
	public class ValidationException : IOException
	{
		public ValidationException() : base()
		{
		}

		public ValidationException(string message) : base(message)
		{
		}
	}

	/// <summary>
	/// Validates data agains a <see cref="HashTree"/> and writes it to a stream.
	/// </summary>
	public class ValidatingOutputStream : Stream
	{
		private HashTree hashTree;
		private Stream outputStream;
		private int startLeaf;
		private long position;

		private HashTree tempTree;
		private byte[] tempBuffer;
		private int bufferPos;
		private int validated;

		/// <summary>
		/// Initializes a new <see cref="ValidatingOutputStream"/> instance.
		/// </summary>
		/// <param name="algorithm">
		/// The algorithm to use when validating. Should be the same as used when
		/// creating the <see cref="HashTree/>.
		/// </param>
		/// <param name="hashTree">The <see cref="HashTree"/> to validate against.</param>
		/// <param name="outputStream">The underlying <see cref="Stream"/></param>
		/// <param name="start">
		/// The position in the <see cref="HashTree"/> that the validation will start at.
		/// </param>
		public ValidatingOutputStream(HashAlgorithm algorithm, HashTree hashTree,
			Stream outputStream, long start) : base()
		{
			if (algorithm == null)
			{
				throw new ArgumentNullException("algorithm");
			}
			if (hashTree == null)
			{
				throw new ArgumentNullException("hashTree");
			}
			if (outputStream == null)
			{
				throw new ArgumentNullException("outputStream");
			}
			if (start % hashTree.BlockSize != 0)
			{
				throw new ArgumentException("Can only validate from the start of a leaf.",
					"start");
			}
			this.hashTree = hashTree;
			this.outputStream = outputStream;

			startLeaf = (int)(start / hashTree.BlockSize);
			position = start;

			tempTree = new HashTree(algorithm, hashTree.BlockSize);
			tempBuffer = new byte[HashTree.SegmentSize];
		}

		#region Properties

		/// <value>
		/// The first leaf that was validated.
		/// </value>
		public int StartLeaf
		{
			get { return startLeaf; }
		}

		/// <value>
		/// The number of validated leaves.
		/// </value>
		public int ValidatedLeaves
		{
			get { return validated; }
		}

		public override bool CanRead
		{
			get { return false; }
		}

		public override bool CanSeek
		{
			get { return false; }
		}

		public override bool CanWrite
		{
			get { return true; }
		}

		public override long Position
		{
			get { return position; }
			set { throw new NotSupportedException(); }
		}

		public override long Length
		{
			get { throw new NotSupportedException(); }
		}

		#endregion

		#region Methods

		public override int Read(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		public override void SetLength (long value)
		{
			throw new NotSupportedException();
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException();
		}

		public override void Flush()
		{
			outputStream.Flush();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			int realOffset = offset;
			int realCount = count;
			int segmentSize = HashTree.SegmentSize;

			// Update the tree
			if (bufferPos + count >= segmentSize)
			{
				if (bufferPos > 0)
				{
					// ...with data from the previous write
					int used = segmentSize - bufferPos;
					Buffer.BlockCopy(buffer, offset, tempBuffer, bufferPos, used);
					bufferPos = 0;

					tempTree.Update(tempBuffer, 0, segmentSize);
					count -= used;
					offset += used;
				}
				while (count >= segmentSize)
				{
					tempTree.Update(buffer, offset, segmentSize);
					count -= segmentSize;
					offset += segmentSize;
				}
			}

			// Handle the remaining data
			if (count > 0)
			{
				Buffer.BlockCopy(buffer, offset, tempBuffer, bufferPos, count);
				bufferPos += count;
			}

			// Handle the last leaf
			if (position + realCount == hashTree.FileSize)
			{
				if (bufferPos > 0)
				{
					tempTree.Update(tempBuffer, 0, bufferPos);
				}
				tempTree.CalculateRoot();
			}

			// Validate and write
			if (tempTree.LeafCount >= validated)
			{
				CompareLeaves();
			}
			outputStream.Write(buffer, realOffset, realCount);
			position += realCount;
		}

		private void CompareLeaves()
		{
			while (validated < tempTree.LeafCount)
			{
				if (!HashTree.LeavesAreEqual(tempTree[validated],
					hashTree[startLeaf + validated]))
				{
					throw new ValidationException("Hash tree mismatch");
				}
				validated++;
			}
		}

		#endregion
	}
}
